<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------

namespace plugins\dingding\controller;

use plugins\dingding\lib\Dingding;
use plugins\dingding\lib\crypto\DingtalkCrypt;
use cmf\controller\PluginBaseController;
use think\Db;
use think\db\Query;

class IndexController extends PluginBaseController
{
    public function index()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'DingTalk') !== false){
            $app = $this->request->param('app');
            $corp = $this->request->param('corp');
            $adm = $this->request->param('adm');
            if(empty($app) || empty($corp))return "钉钉应用未配置或参数不全";
            $ding = new Dingding($corp,$app);


                if($ding){
                    $sessionAdminId = session('ADMIN_ID');
                    if (!empty($sessionAdminId)) {

                        $ding = new Dingding($corp,$app);
                        $admin = $ding->getAdmin();
                        if($adm == '1')$index = 'admin_index';
                        else {
                            if($admin == '1')$index = 'admin_index';
                            else $index = 'index';
                        }

                        return redirect($this->request->root() . '/' . $app .'/' . $index);
                    } else {
                        $this->assign("corpid", $ding->getCorpid());
                        $this->assign("app", $app);
                        $this->assign("corp", $corp);
                        $this->assign("adm", $adm);
                        session("corp", $corp);
                        session("app", $app);
                        return $this->fetch("/admin_login");
                    }
                }
                else return "请联系管理员配置钉钉应用";
            }

            //$appinfo = Db::name('plugin_dingding_app')->where("app",$app)->find();
        else return "请用钉钉打开!";
    }

    public function dologin()
    {
        if($this->request->isPost()){
            $app = $this->request->param('app');
            $corp = $this->request->param('corp');
            $adm = $this->request->param('adm');
            if (strpos($_SERVER['HTTP_USER_AGENT'], 'AliApp') !== false){$aliapp = true;}
            require_once("../vendor/dingding/TopSdk.php");
            $c = new \DingTalkClient(\DingTalkConstant::$CALL_TYPE_OAPI, \DingTalkConstant::$METHOD_GET , \DingTalkConstant::$FORMAT_JSON);
            $ding = new Dingding($corp,$app);
            $admin = $ding->getAdmin();
            $access_token = $ding->getAccessToken();
            if ($access_token) {
                $code = $this->request->post("authCode");
                // 通过authcode和accesstoken获取哦用户信息
                $req = new \OapiUserGetuserinfoRequest;
                $req->setCode($code);
                $resp=$c->execute($req, $access_token,"https://oapi.dingtalk.com/user/getuserinfo");

                if ($resp->errcode == 0) {
                    $req = new \OapiUserGetRequest;
                    $req->setUserid($resp->userid);
                    $resp = $c->execute($req, $access_token,"https://oapi.dingtalk.com/user/get");

                    if ($resp->errcode == 0) {
                        $result = Db::name("user")->where(['mobile'=>$resp->mobile,'user_status'=>1])->find();
                        $user['mobile'] = $resp->mobile;

                        if (empty($result)) {
                            $data   = [
                                'user_login'      => empty($user['user_login']) ? $user['mobile'] : $user['user_login'],
                                'user_email'      => empty($user['user_email']) ? $user['mobile'] . "@139.com" : $user['user_email'],
                                'mobile'          => $user['mobile'],
                                'user_nickname'   => $resp->name,
                                'user_pass'       => cmf_password(cmf_random_string(8)),
                                'last_login_ip'   => get_client_ip(0, true),
                                'create_time'     => time(),
                                'last_login_time' => time(),
                                'user_status'     => 1,
                                "avatar"       => $resp->avatar,//管理员
                            ];
                            $userId = Db::name("user")->insertGetId($data);
                            $data   = Db::name("user")->where('id', $userId)->find();
                            cmf_update_current_user($data);

                            $roledata = [
                                'user_id' => $userId,
                                'role_id' => 999,
                            ];
                            Db::name('RoleUser')->insert($roledata);

                            $token = cmf_generate_user_token($userId, 'web');
                            if (!empty($token)) {
                                session('token', $token);
                            }
                            if($adm == '1') return "权限未分配，请联系管理员分配权限！";
                            else {
                                if($admin == '1')return "权限未分配，请联系管理员分配权限！";
                                else {
                                    return redirect($this->request->root() . '/' . $app);
                                }
                            }
                        } else {
                            if($result['user_type'] == 1){
                                $groups = Db::name('RoleUser')
                                    ->alias("a")
                                    ->join('__ROLE__ b', 'a.role_id =b.id')
                                    ->where(["user_id" => $result["id"], "status" => 1])
                                    ->value("role_id");

                                if ($result["id"] != 1 && (empty($groups) || empty($result['user_status']))) {
                                //if (empty($result['user_status'])) {

                                    return "权限未分配，请联系管理员分配权限！";
                                }

                                $result['user_nickname'] = $resp->name;
                                $result['avatar'] = $resp->avatar;
                                //登入成功页面跳转
                                session('ADMIN_ID', $result["id"]);
                                session('name', $result["user_nickname"]);
                                $result['last_login_ip']   = get_client_ip(0, true);
                                $result['last_login_time'] = time();
                                $token                     = cmf_generate_user_token($result["id"], 'web');
                                if (!empty($token)) {
                                    session('token', $token);
                                }
                                Db::name('user')->update($result);
                                //cookie("admin_username", $name, 3600 * 24 * 30);
                                //session("__LOGIN_BY_CMF_ADMIN_PW__", null);
                                //$this->success(lang('LOGIN_SUCCESS'), url("admin/Index/index"));
                                cmf_update_current_user($result);
                                session('dd_userid', $resp->userid);
                                //session("dd_dept",iso_get_company_by_department($resp->department));
                                //session("dd_dept",$resp->department);

                                if($adm == '1')$index = 'admin_index';
                                else {
                                    if($admin == '1')$index = 'admin_index';
                                    else $index = 'index';
                                }

                                return redirect($this->request->root() . '/' . $app .'/' . $index);

                            }
                            else {
                                return "权限未分配，请联系管理员分配权限！";
                            }
                        }



                    } else {
                        return '获取用户信息错误，'.$resp->errmsg;
                    }
                } else {

                    return '获取用户ID错误，'.$resp->errmsg;
                }

            }
            else return '无法获取access_token';
        }
    }

    public function dt_callback_reg(){
        $params = $this->request->param();
        $corp = $params['corp'];
        $app = $params['app'];
        if(empty($corp) || empty($app))return;
        $ding = new Dingding($corp,$app);
        $corpid = $ding->getCorpid();
        $url = 'http://fz.cmttfj.com/plugin/dingding/index/eventreceive/corpid/' . $corpid;
        $result= $ding->callback_reg($url,["bpms_instance_change"]);

        print_r($result);
    }

    public function dt_callback_update(){
        $params = $this->request->param();
        $corp = $params['corp'];
        $app = $params['app'];
        if(empty($corp) || empty($app))return;
        $ding = new Dingding($corp,$app);
        $corpid = $ding->getCorpid();
        $url = 'http://fz.cmttfj.com/plugin/dingding/index/eventreceive/corpid/' . $corpid;
        $result= $ding->callback_reg($url);

        print_r($result);
    }

    public function eventreceive(){
        $params = $this->request->param();

            $aeskey = '1234567890123456789012345678901234567890123';
            $token = '123456';
            //$app = $params['app'];
            //$ding = new Dingding($corp,$app);
            $corpid = $params['corpid'];
            $crypt = new DingtalkCrypt($token, $aeskey, $corpid);

            //$msg = "success";
            $encryptMsg = "";
            $timeStamp = $params['timestamp'];
            $nonce = $params['nonce'];
            $signature = $params['signature'];
            $encrypt = $params['encrypt'];
            $msg = "";
            $errCode = $crypt->DecryptMsg($signature, $timeStamp, $nonce, $encrypt, $msg);

            if ($errCode == 0)
            {
                $eventMsg = json_decode($msg);
                $eventType = $eventMsg->EventType;
                //$EventType = "check_url";
                if(!empty($eventType)){
                    if($eventType == 'bpms_instance_change'){
                        $this->do_bpms_instance_change($eventMsg);
                    }
                    $res = "success";
                    $encryptMsg = "";
                    $errCode = $crypt->EncryptMsg($res, $timeStamp, $nonce, $encryptMsg);
                    if ($errCode == 0)
                    {
                        cmf_log("RESPONSE: " . $encryptMsg);
                        return $encryptMsg;
                    }
                    else
                    {
                        cmf_log("RESPONSE ERR: " . $errCode);
                    }
                }
            }
            else
            {
                cmf_log(json_encode($_GET) . "  ERR:" . $errCode);

            }
    }

    protected function do_bpms_instance_change($encryptMsg){
        $type = $encryptMsg->type;

        if($type == 'finish'){
            $result = $encryptMsg->result;
            if(!empty($result)){
                if($result == 'agree'){

                    $procode = $encryptMsg->processCode;

                    $sense = Db::name("plugin_dingding_sense")->where('procode',$procode)->find();
                    if(!empty($sense)){
                        $corp = $sense['corp'];
                        $app = $sense['app'];

                        $ding = new Dingding($corp,$app);
                        $proinsid = $encryptMsg->processInstanceId;

                        $proresult = $ding->get_process_detail($proinsid);

                        $prodata = json_encode($proresult->process_instance->form_component_values);

                        $create_time = $proresult->process_instance->create_time;
                        $dd_userid = $proresult->process_instance->originator_userid;
                        $corpid = $ding->getCorpid();
                        $user = Db::name('dduser')->where(['userid'=>$dd_userid,'corpid'=>$corpid])->find();
                        if(empty($user)){
                            $user = $ding->get_user($dd_userid);
                        }
                        if(!empty($user)) {
                            $data['user_nickname'] = $user['username'];
                            $data['user_mobile'] = $user['mobile'];
                        }
                        $data['create_time'] = $create_time;
                        $data['prodata'] = $prodata;
                        $data['sense'] = $sense['sense'];
                        $data['procode'] = $procode;
                        $data['proinsid'] = $proinsid;
                        //$upinfo_model = new UpinfoModel();
                        $tablename = $app . "_data";
                        Db::name($tablename)->insertGetId($data);

                    }
                }
            }

        }
    }
}
